package zuosheng.string;

/**
 * @author lj
 * @Description: 翻转字符串
 * @date 2020-11-15 14:51
 * @QQ 851477108
 */


public class RotateWord {
    public static void main(String[] args) {
        String str = "Java love I";
        char[] chars = str.toCharArray();
        rotateWord(chars);
        System.out.print(chars);
    }

    public static void rotateWord(char[] c){
        if (c == null || c.length == 0){
            return;
        }

        reverse(c, 0, c.length - 1);

        int left = -1;
        int right = -1;
        for (int i = 0; i < c.length; i++){
            //找到单词边界[l,r]
            if(c[i] != ' '){
                left = i == 0 || c[i-1] == ' ' ? i : left;
                right = i == c.length - 1 || c[i+1] == ' ' ? i : right;
            }
            //根据边界第二次翻转得到原来的意思
            if (left != -1 && right != -1){
                reverse(c, left , right);
                left = -1;
                right = -1;
            }
        }
    }

    //翻转函数
    public static void reverse(char[] chars, int start, int end){
        char temp = 0;
        while (start < end){
            temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }
}
